# -*- coding: utf-8 -*-
# @Time : 2022/6/25 22:30
# @Author : zgj
# @File : cmd_utils.py
import os
import subprocess
import time
from loguru import logger
from app.commons.exceptions.global_exception import BusinessException

# 设置最大重试次数
MAX_RETRIES = 3
# 设置重试间隔时间（秒）
RETRY_INTERVAL = 1


class CmdUtils(object):

    @staticmethod
    def cmd(cmd_str: str, timeout: int = 10):
        """
        执行shell命令
        :param cmd_str: 字符串命令
        :param timeout: 超时时间
        :return:
        """
        logger.info(f"执行的时长: {timeout}")
        retries = 0
        while retries < MAX_RETRIES:
            try:
                logger.info(f"执行的命令: {cmd_str}")
                p = subprocess.Popen([cmd_str], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                     encoding='utf-8')
                return p
            except Exception as e:
                retries += 1
                if retries < MAX_RETRIES:
                    logger.error(f"{cmd_str} 命令执行失败（第{retries}次重试）, 错误信息: {str(e)}")
                    logger.info(f"等待{RETRY_INTERVAL}秒后进行下一次重试...")
                    time.sleep(RETRY_INTERVAL)
                else:
                    logger.error(f"{cmd_str} 命令经过{MAX_RETRIES}次重试后执行失败, 错误信息: {str(e)}")
                    raise BusinessException(f"命令执行失败!!! ")
        # try: logger.info(f"执行的命令: {cmd_str}") p = subprocess.Popen([cmd_str], shell=True, stdout=subprocess.PIPE,
        # stderr=subprocess.PIPE, encoding='utf-8') return p except Exception as e: logger.error(f"{cmd_str} 命令执行失败,
        # 错误信息: {str(e)}") raise BusinessException(f"命令执行失败!!! ")

    @staticmethod
    def check_directory_exists(path, target_directory):
        """
        检查指定路径下是否存在目标目录。

        :param path: 要检查的路径
        :param target_directory: 要查找的目标目录名称
        :return: 如果目标目录存在于路径下则返回 True，否则返回 False
        """
        full_path = os.path.join(path, target_directory)
        return os.path.isdir(full_path)
